package com.liuzhu.chaoshikucungunli.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ImageButton;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.liuzhu.chaoshikucungunli.R;
import com.liuzhu.chaoshikucungunli.model.Product;
import java.util.ArrayList;
import java.util.List;

public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ProductViewHolder> {
    
    private List<Product> products = new ArrayList<>();
    private OnProductIntroClickListener introClickListener;
    
    // 添加接口定义
    public interface OnProductIntroClickListener {
        void onIntroClick(Product product);
    }
    
    // 设置监听器的方法
    public void setOnProductIntroClickListener(OnProductIntroClickListener listener) {
        this.introClickListener = listener;
    }
    
    @NonNull
    @Override
    public ProductViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_product, parent, false);
        return new ProductViewHolder(view);
    }
    
    @Override
    public void onBindViewHolder(@NonNull ProductViewHolder holder, int position) {
        Product product = products.get(position);
        holder.nameText.setText(product.getName());
        holder.quantityText.setText("剩余数量: " + product.getQuantity());
        
        // 设置商品图片
        if (product.getImageResId() != 0) {
            holder.productImage.setImageResource(product.getImageResId());
        } else {
            // 设置默认图片
            holder.productImage.setImageResource(R.drawable.default_product);
        }
        
        // 设置介绍按钮点击事件
        holder.introButton.setOnClickListener(v -> {
            if (introClickListener != null) {
                introClickListener.onIntroClick(product);
            }
        });
    }
    
    @Override
    public int getItemCount() {
        return products.size();
    }
    
    public void setProducts(List<Product> products) {
        this.products = products;
        notifyDataSetChanged();
    }
    
    static class ProductViewHolder extends RecyclerView.ViewHolder {
        ImageView productImage;
        TextView nameText;
        TextView quantityText;
        ImageButton introButton;
        
        ProductViewHolder(View itemView) {
            super(itemView);
            productImage = itemView.findViewById(R.id.product_image);
            nameText = itemView.findViewById(R.id.product_name);
            quantityText = itemView.findViewById(R.id.product_quantity);
            introButton = itemView.findViewById(R.id.btn_product_intro);
        }
    }
} 